<template>
  <div class="equipment-info bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-6">公用工程实时在线监测</h2>

    <!-- 搜索表单 -->
    <div class="bg-card text-card-foreground p-6 rounded-lg shadow-sm mb-6">
      <button v-for="btn in btnname" :key="btn" @click="btnsubmit(btn)"
        style="background-color:rgba(22, 155, 213, 1);margin:0 10px;width: 100px;" class="btn btn-primary">{{ btn
        }}</button>
      <button style="margin-left: 15px;" @click="exportData" class="btn btn-secondary">导出</button>
    </div>
    <!-- 数据表格 -->
    <div class="bg-card text-card-foreground rounded-lg shadow-sm overflow-hidden">
      <table class="w-full">
        <thead>
          <tr class="bg-muted text-muted-foreground">
            <th v-for="header in tableHeaders" :key="header" class="p-3 text-left">{{ header }}</th>
            <!-- <th class="p-3 text-left">操作</th> -->
          </tr>
        </thead>
        <tbody>
          <tr v-for="equipment in equipmentData" :key="equipment.id" class="border-t border-border">
            <td class="p-3">{{ equipment.company }}</td>
            <td class="p-3">{{ equipment.press }}</td>
            <td class="p-3">{{ equipment.degree_heat }}</td>
            <td class="p-3">{{ equipment.density }}</td>
            <td class="p-3">{{ equipment.fre }}</td>
            <td class="p-3">{{ equipment.heat_s }}</td>
            <td class="p-3">{{ equipment.heat_all }}</td>
            <td class="p-3">{{ equipment.state }}</td>
            <!-- <td class="p-3">
              <button @click="editEquipment(equipment)" class="btn btn-sm btn-secondary mr-2">编辑</button>
              <button @click="viewEquipment(equipment)" class="btn btn-sm btn-secondary">查看</button>
            </td> -->
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <!-- <div class="mt-6 flex justify-between items-center">
      <span>共 {{ totalItems }} 条记录</span>
      <div class="space-x-2">
        <button v-for="page in totalPages" :key="page" @click="currentPage = page"
          :class="['btn btn-sm', currentPage === page ? 'btn-primary' : 'btn-secondary']">
          {{ page }}
        </button>
      </div>
    </div> -->


  </div>
</template>


<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import * as XLSX from 'xlsx'

const apiBaseUrl = ref(proxy.$currentUrl + '/api/gongre')
const search = ref({
  EQUIP_NUM: '',
  EQUIP_NAME: '',
  EQUIP_TYPE: '',
  EQUIP_STATE: ''
})

function tabelname (str) {
  const name = {
    'water': [{ "zh": "水质PH值", "eh": "water_ph" },
    { "zh": "浊度（NTU）", "eh": "water_ntu" },
    { "zh": "氯含量（mg/L）", "eh": "water_cl" },
    { "zh": "细菌总数（CFU/ml）", "eh": "water_cfu" },
    { "zh": "重金属含量（mg/L）", "eh": "water_hm" },
    { "zh": "流量（T/h）", "eh": "water_traffic" },
    { "zh": "耗水量/万立方米", "eh": "water_cost" }
    ],

    'sewage': [
      { "zh": "COD (mg/L)", "eh": "sewage_cod" },
      { "zh": "氨氮 (mg/L)", "eh": "sewage_nn" },
      { "zh": "总磷（mg/L）", "eh": "sewage_p" },
      { "zh": "总氮（mg/L）", "eh": "sewage_n" },
      { "zh": "pH值", "eh": "sewage_ph" },
      { "zh": "液位（M）", "eh": "sewage_height" },
      { "zh": "中水回用率（%）", "eh": "sewage_reuse" }
    ],

    'electric': [
      { "zh": "电压水平（V）", "eh": "electric_voltage" },
      { "zh": "电流水平（A）", "eh": "electric_current" },
      { "zh": "功率因数", "eh": "electric_power" },
      { "zh": "频率(Hz)", "eh": "electric_fre" },
      { "zh": "电压波动 (%)", "eh": "electric_voltage_flu" },
      { "zh": "耗电量/万千瓦时", "eh": "electric_cost" }
    ],

    'gas': [
      { "zh": "气体浓度（ppm）", "eh": "gas_ppm" },
      { "zh": "压力（psi）", "eh": "gas_press" },
      { "zh": "温度（°C）", "eh": "gas_temp" },
      { "zh": "湿度（%）", "eh": "gas_wet" },
      { "zh": "耗气量/万立方米", "eh": "gas_cost" }
    ],

    'mo': [
      { "zh": "压力（Mpa）", "eh": "press" },
      { "zh": "温度（°C）", "eh": "degree_heat" },
      { "zh": "密度（kg/m³）", "eh": "density" },
      { "zh": "频率（Hz）", "eh": "fre" },
      { "zh": "瞬时热量（GJ/h）", "eh": "heat_s" },
      { "zh": "累计量（GJ）", "eh": "heat_all" }
    ],

    'toxic': [
      { "zh": "二氧化硫(ppm)", "eh": "toxic_so2" },
      { "zh": "氮氧化物（ppm)", "eh": "toxic_no" },
      { "zh": "氯化氢(ppm)", "eh": "toxic_hcl" },
      { "zh": "非甲烷总烃(ppm)", "eh": "toxic_chn" },
      { "zh": "颗粒物(μg/m³)", "eh": "toxic_pm" },
      { "zh": "氮（ppm）", "eh": "toxic_n" },
      { "zh": "重金属含量（μg/m³）", "eh": "toxic_hm" }
    ],
  }
  name[str].push('状态')
  return name[str]
}

const btnname = [
  {},
  {},
  {},
  {}
  // '水', '污水', '电力', '天然气', '供热', '有毒气体'
]

const defintable = ref('水')


const tableHeaders = ref([
  '机构/企业', ...tabelname(defintable.value)
])

const btnsubmit = (item) => {
  tableHeaders.value = ['机构/企业']
  tableHeaders.value.push(...tabelname(item))
}
const equipmentData = ref([])
const currentPage = ref(1)
const pageSize = 10
const selectAll = ref(false)
const showDialog = ref(false)
const isEditing = ref(false)
const currentEquipment = ref({
  PARK_CODE: '',// 园区编号
  EQUIP_NAME: '', //设备名称
  EQUIP_TYPE: '',//设备类型: 1 门禁, 2 人员闸机, 3 车辆卡口, 4 车辆抓拍道闸
  LONGITUDE: '',// 经度
  LATITUDE: '',//纬度
  COMPANY_NAME: '',//公司名称
  EQUIP_ADDR: '',//设备地址
  EQUIP_STATE: '',//设备状态：1.正常，2闲置，3损坏
  EQUIP_CRE: '',//生产厂家
  EQUIP_CODE: '',//型号
  EQUIP_NUM: '',//设备编码
  BUS_NUM: ''
})

const totalItems = computed(() => equipmentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize))

const displayedEquipment = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return equipmentData.value.slice(start, end)
})
const deleteUpdateBy = ref('')
const searchEquipment = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    equipmentData.value = response.data.map((item) => ({
      ...item,
      selected: false,
    }))

  } catch (error) {
    alert(
      '搜索失败'
    )
  }

  // 实现搜索逻辑
  console.log('Searching equipment:', search.value)
}

const resetSearch = () => {
  search.value = {
    EQUIP_NUM: '',
    EQUIP_NAME: '',
    EQUIP_TYPE: '',
    EQUIP_STATE: ''
  }
  getAllserch()
}

const addEquipment = () => {
  isEditing.value = false

  showDialog.value = true
}

const editEquipment = (equipment) => {
  isEditing.value = true
  currentEquipment.value = { ...equipment }
  showDialog.value = true
}

const viewEquipment = (equipment) => {
  // 实现查看设备详情逻辑
  console.log('Viewing equipment:', equipment)
}




// 添加 s2ab 辅助函数
function s2ab (s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF
  return buf
}

const exportData = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new()

  // 准备要导出的数据
  const exportData = equipmentData.value.map(record => ({
    '机构/企业': record.company,
    '压力（Mpa）': record.press,
    '温度（°C）': record.degree_heat,
    '密度（kg/m³）': record.density,
    '频率（Hz）': record.fre,
    '瞬时热量（GJ/h）': record.heat_s,
    '累计量（GJ）': record.heat_all,
    '状态': record.state,
  }))

  // 将数据转换为工作表
  const ws = XLSX.utils.json_to_sheet(exportData)

  // 将工作表添加到工作簿，并设置表名为"值班管理"
  XLSX.utils.book_append_sheet(wb, ws, "供热检测表")

  // 生成二进制字符串
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为 Blob
  const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" })

  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '供热检测表.xlsx'

  // 模拟点击下载
  link.click()

  // 释放 URL 对象
  URL.revokeObjectURL(link.href)
}

const toggleSelectAll = () => {
  equipmentData.value.forEach(equipment => equipment.selected = selectAll.value)
}

const closeDialog = () => {
  showDialog.value = false
}





const getAllserch = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}`)
    equipmentData.value = response.data
  } catch (error) {
    console.log(error)
    alert(
      '搜索失败'
    )
  }
}


onMounted(() => {

  getAllserch()
})
</script>

<style scoped>
.input,
.select {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply h-4 w-4 text-primary focus:ring-primary border-input rounded;
}
</style>
